// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: GPL-3.0-or-later

package xyz.apiote.bimba.czwek.repo

import android.content.Context
import android.net.ConnectivityManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import xyz.apiote.bimba.czwek.api.Server
import xyz.apiote.bimba.czwek.api.responses.FeedsResponse
import xyz.apiote.bimba.czwek.api.responses.FeedsResponseDev
import xyz.apiote.bimba.czwek.api.responses.FeedsResponseV1
import xyz.apiote.bimba.czwek.api.responses.FeedsResponseV2
import java.io.File
import java.io.FileInputStream
import java.net.URLEncoder

class OfflineRepository : Repository {
	override suspend fun getFeeds(
		context: Context,
		server: Server
	): Map<String, FeedInfo>? {
		val file = File(
			context.filesDir, URLEncoder.encode(server.apiPath, "utf-8")
		)
		if (!file.exists()) {
			return emptyMap()
		}
		return when (val response =
			withContext(Dispatchers.IO) { FeedsResponse.unmarshal(FileInputStream(file)) }) {
			is FeedsResponseDev -> response.feeds.associate {
				Pair(
					it.id,
					FeedInfo(it).copy(cached = true)
				)
			}

			is FeedsResponseV2 -> response.feeds.associate {
				Pair(
					it.id,
					FeedInfo(it).copy(cached = true)
				)
			}

			is FeedsResponseV1 -> response.feeds.associate {
				Pair(
					it.id,
					FeedInfo(it).copy(cached = true)
				)
			}

			else -> null
		}
	}

	override suspend fun getDepartures(
		feedID: String,
		stop: String,
		line: String?,
		context: Context,
		limit: Int?
	): StopDepartures? {
		TODO("Not yet implemented")
	}

	override suspend fun getLocatablesIn(
		cm: ConnectivityManager,
		bl: Position,
		tr: Position,
		context: Context
	): List<Locatable>? {
		TODO("Not yet implemented")
	}

	override suspend fun getLine(
		cm: ConnectivityManager,
		feedID: String,
		line: String,
		context: Context
	): Line? {
		TODO("Not yet implemented")
	}

	override suspend fun queryQueryables(
		query: String,
		context: Context
	): List<Queryable>? {
		TODO("Not yet implemented")
	}

	override suspend fun locateQueryables(
		position: Position,
		context: Context
	): List<Queryable>? {
		TODO("Not yet implemented")
	}

}
